(function () {
    "use strict";

    angular.module('core').controller('vendaVarejoController', controller);
    controller.$inject = ['$scope', '$timeout', '$q', '$stateParams', '$alert', 'vendaVarejoService'];

    function controller($scope, $timeout, $q, $stateParams, $alert, vendaVarejoService) {
        $scope.initializeLayout('Vendas de Varejo');

        //[Inicializa objetos]
        $scope.state = {
            data: [],
            carregando: false,
            vazio: false,
            count: 0,
            filtro: {
                ativo: false,
                args: {}
            }
        };

        //[Inicializa funcões]
        $scope.initialize = async () => {
            await $scope.clearFilter();

            const _filtro = $scope.localStorage.getItem('state.filtro.args');
            if (_filtro) {
                await angular.copy(_filtro, $scope.state.filtro.args);
            }

            if ($stateParams.id)
                $scope.popups.edit.toggle($stateParams.id);

            $scope.refresh();
        };

        $scope.beforeRefresh = async () => {
            await $scope.convertFilter();
        };
        $scope.afterRefresh = async () => {
            /* trata mudanças no filtro */
            $scope.state.filtro.original.sortExpression = $scope.state.filtro.args.sortExpression;
            $scope.state.filtro.original.skip = $scope.state.filtro.args.skip;
            $scope.state.filtro.original.take = $scope.state.filtro.args.take;

            $scope.state.filtro.hasChanges = (angular.toJson($scope.state.filtro.original) !== angular.toJson($scope.state.filtro.args));

            /* armazena na localstorage para quando inicializar a página */
            $scope.localStorage.setItem('state.filtro.args', $scope.state.filtro.args);
        };
        $scope.refresh = async () => {
            try {
                await $scope.beforeRefresh();
                $scope.state.filtro.ativo = false;
                await $scope.innerRefresh();
                await $scope.afterRefresh();
            }
            catch (error) {
                console.error(error);
                $scope.clearFilter();
            } finally {
                $scope.$digest();
            }
        };
        $scope.clear = async () => {
            await $scope.clearFilter();
            $scope.refresh();
        };

        $scope.toggleFilter = async () => {
            $scope.state.filtro.ativo = !$scope.state.filtro.ativo;
        };
        $scope.convertFilter = async () => {
            /* prepara o filtro. Ex: in list de status */
        };
        $scope.clearFilter = async () => {
            $scope.state.filtro = {
                args: {
                    chaves: '',
                    filtro: null,
                    filtroDe: {
                        Emissao: $scope.tools.date.getNMesesAtras(1)
                    },
                    filtroAte: {
                        Emissao: $scope.tools.date.hoje
                    },
                    sortExpression: '[Emissao] desc, [Codigo]',
                    skip: 0,
                    take: 20
                },
                original: {},
                hasChanges: false
            };

            await $scope.convertFilter();
            await angular.copy($scope.state.filtro.args, $scope.state.filtro.original);
        };

        $scope.innerRefresh = async () => {

            await $scope.getAll();
            await $scope.count();

            $scope.$digest();
        };
        $scope.getAll = async () => {
            try {
                $scope.state.filtro.args.skip = 0;
                $scope.state.carregando = true;
                $scope.state.vazio = false;

                let response = await vendaVarejoService.getAll($scope.state.filtro.args)
                if (response.Status < 0) {
                    $scope.tools.toastr.error(response.Message, 'Serviço');
                } else {
                    angular.copy(angular.fromJson(response.Data), $scope.state.data);
                }
                $scope.state.vazio = ($scope.state.data == 0);
            }
            catch (error) {
                $scope.tools.toastr.error('Não foi possível conectar com o(s) servidor(es)');
            }
            finally {
                $scope.state.carregando = false;
            }
        };
        $scope.count = async () => {
            try {
                let response = await vendaVarejoService.count($scope.state.filtro.args)
                if (response.Status < 0) {
                    $scope.tools.toastr.error(response.Message, 'Serviço');
                } else {
                    $scope.state.count = response.Data;
                }
            } catch (error) {
                $scope.tools.toastr.error('Não foi possível conectar com o(s) servidor(es)');
            } finally {
            }
        };
        $scope.getMore = async () => {
            if (!$scope.state.carregandoMais && !$scope.state.carregando && !$scope.state.completo && !($scope.state.data == 0)) {
                $scope.state.carregandoMais = true;
                try {
                    $scope.state.filtro.args.skip += $scope.state.filtro.args.take;

                    let response = await vendaVarejoService.getAll($scope.state.filtro.args);
                    if (response.Status < 0) {
                        $scope.tools.toastr.error(response.Message, 'Serviço');
                    } else {
                        $scope.state.data = $scope.state.data.concat(response.Data);
                    }
                } catch (error) {
                    $scope.tools.toastr.error('Não foi possível conectar com o(s) servidor(es)');
                } finally {
                    $scope.state.carregandoMais = false;
                    $scope.$apply();
                }
            }
        };

        /*Inicializa funções*/
        $scope.initialize();

    }

})();